import { Button, Form, message, Modal, Select } from 'antd';
import React, { useEffect, useState } from 'react';
import { listBankUsingPost } from '@/api/BankApi';
import { addQuestionToBankBatchUsingPost } from '@/api/QuestionBankMapApi';

interface Props {
  questionIdList?: number[];
  visible: boolean;
  onSubmit: () => void;
  onCancel: () => void;
}

/**
 * 批量添加题目到题库
 * @param props
 * @constructor
 */
const AddBankBatchModal: React.FC<Props> = (props) => {
  const { questionIdList = [], visible, onSubmit, onCancel } = props;
  const [form] = Form.useForm();
  const [bankList, setBankList] = useState<API.QuestionBank[]>([]);
  const pageSize = 200;

  const getBankList = async () => {
    try {
      const res = await listBankUsingPost({
        pageSize,
        sortField: 'createTime',
        sortOrder: 'desc',
      });
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      setBankList(res.data.records ?? []);
    } catch (e) {
      console.log('获取题库列表失败:', e.message);
    }
  };

  const handleSubmit = async (values: API.QuestionBankMapAddBatchDto) => {
    const hide = message.loading('正在操作中...');
    const bankId = values.bankId;
    if (!bankId) {
      return;
    }
    try {
      await addQuestionToBankBatchUsingPost({
        bankId,
        questionIdList,
      });
      hide();
      message.success('操作成功');
      onSubmit?.();
    } catch (e) {
      hide();
      message.error('操作失败.' + e.message);
      return false;
    }
  };

  useEffect(() => {
    getBankList();
  }, []);

  return (
    <Modal
      destroyOnClose
      title={'批量添加题目到题库'}
      open={visible}
      footer={null}
      onCancel={() => {
        onCancel?.();
      }}
    >
      <Form form={form} style={{ marginTop: 24 }} onFinish={handleSubmit}>
        <Form.Item label={'选择题库'} name={'bankId'}>
          <Select
            style={{ width: '100%' }}
            options={bankList.map((item) => {
              return {
                label: item.title,
                value: item.id,
              };
            })}
          />
        </Form.Item>
        <Form.Item>
          <Button type={'primary'} htmlType={'submit'}>
            提交
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddBankBatchModal;
